import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


public class Message implements IMessage {

	int messageId;
	DataObject key = null;
	DataObject value = null;
	IMachine source,dest;
	
	@Override
	public DataObject getKey() {
		return this.key;
	}

	@Override
	public int getMessageID() {
		return this.messageId;
	}

	@Override
	public DataObject getValue() {
		return this.value;
	}

	@Override
	public IMachine getDest() {
		return this.dest;
	}

	@Override
	public IMachine getSource() {
		return this.source;
	}

	@Override
	public void setDest(IMachine machine) {
		this.dest = machine;
	}

	@Override
	public void setSource(IMachine machine) {
		this.source = machine;
	}

	@Override
	public void setKey(DataObject key) {
		this.key = key;
	}

	@Override
	public void setValue(DataObject value) {
		this.value = value;
	}

	@Override
	public void setMessageID(int messageId) {
		this.messageId = messageId;
	}

	@Override
	public IMessage deserialize(byte[] data) {
		IMessage message = this;
		ByteArrayInputStream bis = new ByteArrayInputStream(data);
		message.setMessageID(bis.read());
		int keylen = bis.read();
		DataObject key = new DataObject(new byte[keylen]);
		bis.read(key.getVal(), 0, keylen);
		message.setKey(key);
		
		int valuelen = bis.read();
		DataObject val = new DataObject(new byte[valuelen]);
		bis.read(val.getVal(), 0, valuelen);
		message.setValue(val);
		
		return message;
	}

	@Override
	public byte[] serialize()
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataObject key = getKey();
		DataObject value = getValue();
		//message id, key size,key,value size,value		
		try 
		{			
			bos.write(messageId);			
			bos.write(key.length);
			bos.write(key.getVal());
			bos.write(value.length);
			bos.write(value.getVal());
		}
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		return bos.toByteArray();
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("Id: " + this.messageId)
			.append(",")
			.append("Key: " + new String(this.key.getVal()))
			.append(",")
			.append("Value: " + new String(this.value.getVal()))
			;
		return sb.toString();
	}

}
